package com.example.mail;

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Classname Mail
 * @Description TODO
 * @Date 2023/4/28 13:21
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class Mail {



    public static void send(String to, String subject, String body) throws Exception {






        String smtpHost = "smtp.qq.com"; // SMTP服务器地址
        int smtpPort = 25; // SMTP服务器端口号
        String username =  "2532223478@qq.com"; // 发送方邮箱地址
        String password = "drrebdnlvifmeagj"; // 发件人邮箱密码或授权码

        String content = "To: " + to + "\r\n" +
                "Subject: " + subject + "\r\n\r\n" +
                body;

        URL url = new URL("smtp://" + smtpHost + ":" + smtpPort);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        writer.write("HELO " + smtpHost + "\r\n");
        writer.write("AUTH LOGIN\r\n");
        writer.write(new sun.misc.BASE64Encoder().encode(username.getBytes()) + "\r\n");
        writer.write(new sun.misc.BASE64Encoder().encode(password.getBytes()) + "\r\n");
        writer.write("MAIL FROM:<" + username + ">\r\n");
        writer.write("RCPT TO:<" + to + ">\r\n");
        writer.write("DATA\r\n");
        writer.write(content);
        writer.write("\r\n.\r\n");
        writer.write("QUIT\r\n");
        writer.flush();
        writer.close();
    }

    public static void main(String[] args) {
        String to = "xiongxiong9018@sina.com"; // 接收方邮箱地址
        String subject = "Test Email";
        String body = "This is a test email sent from Java.";

        try {
            send(to, subject, body);
            System.out.println("Email sent successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
